package org.example;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.text.DecimalFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 实时收入小窗口类
 */
public class MiniEarningsWindow extends JFrame {
    static final Logger logger = LoggerFactory.getLogger(MiniEarningsWindow.class);
    private JLabel earningsLabel;
    private final DecimalFormat decimalFormat;
    private boolean isWindowTop;
    private final SalaryCalculatorGUI mainWindow;

    public MiniEarningsWindow(SalaryCalculatorGUI mainWindow) {
        // 设置窗口属性
        setUndecorated(true);
        setAlwaysOnTop(true);
        setSize(200, 100);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        // 使用与大窗口相同的图标路径
        try {
            URL iconUrl = getClass().getResource("/images/app_icon.png");
            if (iconUrl != null) {
                Image windowIcon = ImageIO.read(iconUrl);
                setIconImage(windowIcon);
            }
        } catch (IOException e) {
            System.err.println("小窗口图标加载失败: " + e.getMessage());
        }

        this.mainWindow = mainWindow;
        decimalFormat = new DecimalFormat("0.00");
        isWindowTop = true; // 默认置顶
        initializeUI();
        // 初始化显示0.00
        earningsLabel.setText("0.00");
        // 设置窗口始终置顶
        setAlwaysOnTop(true);

        // 添加窗口监听器，确保在窗口关闭时显示主窗口
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                mainWindow.setVisible(true);
            }
        });
    }

    private void initializeUI() {
        setTitle("实时收入");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(200, 120);
        setLocationRelativeTo(null);
        setResizable(false);
        setUndecorated(true); // 无边框窗口

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
        mainPanel.setBorder(new EmptyBorder(10, 10, 5, 10));

        mainPanel.setBackground(new Color(44, 62, 80));

        // 创建右上角退出按钮面板
        JPanel exitPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        exitPanel.setOpaque(false);

        // 收入标签
        earningsLabel = new JLabel("0.00");
        earningsLabel.setFont(new Font("微软雅黑", Font.BOLD, 40));
        earningsLabel.setForeground(Color.WHITE);
        earningsLabel.setHorizontalAlignment(SwingConstants.CENTER);


        JButton closeButton = createImageButton("/images/back_icon.png", e -> {
            mainWindow.setVisible(true);  // 显示主窗口
            this.dispose();  // 销毁小窗口
            logger.info("back to main window");
        });
        closeButton.setBackground(new Color(231, 76, 60));
        closeButton.setPreferredSize(new Dimension(30, 30));
        closeButton.setBorderPainted(false);
        closeButton.setFocusPainted(false);
        closeButton.setContentAreaFilled(true); // 启用内容区域填充以显示背景色

        // 控制按钮面板
        JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        controlPanel.setOpaque(false);
        controlPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));

        // 开始按钮
        JButton startButton = createImageButton("/images/start_icon.png", e -> mainWindow.startWork());

        // 暂停按钮
        JButton pauseButton = createImageButton("/images/pause_icon.png", e -> mainWindow.pauseWork());

        // 结束按钮
        JButton endButton = createImageButton("/images/stop_icon.png", e -> mainWindow.endWork());

        controlPanel.add(startButton);
        controlPanel.add(pauseButton);
        controlPanel.add(endButton);
        controlPanel.add(closeButton);

        // 添加组件
        mainPanel.add(earningsLabel, BorderLayout.CENTER);
        mainPanel.add(controlPanel, BorderLayout.SOUTH);

        // 添加拖动功能
        addDragListener(mainPanel);

        add(mainPanel);
    }

    private JButton createImageButton(String imagePath, ActionListener listener) {
        JButton button = new JButton();
        try {
            // 统一使用类加载器获取资源URL
            URL imgUrl = getClass().getResource(imagePath);
            if (imgUrl == null) {
                throw new FileNotFoundException("资源未找到: " + imagePath);
            }

            // 使用ImageIO直接读取URL
            ImageIcon icon = new ImageIcon(ImageIO.read(imgUrl));

            // 调整图片大小
            Image img = icon.getImage().getScaledInstance(30, 30, Image.SCALE_SMOOTH);
            button.setIcon(new ImageIcon(img));

            button.setBorderPainted(false);
            button.setContentAreaFilled(false);
            button.setFocusPainted(false);
            button.addActionListener(listener);
            button.setPreferredSize(new Dimension(35, 35));

            // 添加鼠标悬停效果
            button.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    button.setCursor(new Cursor(Cursor.HAND_CURSOR));
                }

                public void mouseExited(java.awt.event.MouseEvent evt) {
                    button.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                }
            });

        } catch (Exception e) {
            System.err.println("图片加载失败 - 路径: " + imagePath);
            System.err.println("详细错误: " + e.getClass().getSimpleName() + ": " + e.getMessage());

            // 图片加载失败时使用带颜色的文本按钮
            String buttonText = "";
            Color bgColor = Color.LIGHT_GRAY;

            if (imagePath.contains("start")) {
                buttonText = "▶";
                bgColor = new Color(46, 204, 113);
            } else if (imagePath.contains("pause")) {
                buttonText = "⏸";
                bgColor = new Color(241, 196, 15);
            } else if (imagePath.contains("stop")) {
                buttonText = "⏹";
                bgColor = new Color(231, 76, 60);
            }

            button.setText(buttonText);
            button.setFont(new Font("微软雅黑", Font.BOLD, 16));
            button.setForeground(Color.WHITE);
            button.setBackground(bgColor);
            button.setContentAreaFilled(true);
            button.setBorderPainted(true);
            button.setMargin(new Insets(2, 2, 2, 2));

            // 打印调试信息
            System.out.println("创建回退按钮: " + buttonText + ", 颜色: " + bgColor);
        }
        return button;
    }

    /**
     * 更新显示的收入金额
     */
    public void updateEarnings(double amount) {
        // 处理NaN和无限大的情况
        if (Double.isNaN(amount) || Double.isInfinite(amount)) {
            earningsLabel.setText("0.00");
        } else {
            logger.info("mini window todayEarnings: " + amount);
            earningsLabel.setText(decimalFormat.format(amount));
        }
    }

    /**
     * 设置窗口置顶状态
     */
    public void setWindowTop(boolean top) {
        // 小窗口始终保持置顶，忽略参数
        isWindowTop = true;
        setAlwaysOnTop(true);
    }

    /**
     * 添加窗口拖动功能
     */
    private void addDragListener(JPanel panel) {
        Point origin = new Point();
        panel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent e) {
                origin.x = e.getX();
                origin.y = e.getY();
            }
        });

        panel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent e) {
                Point p = getLocation();
                setLocation(p.x + e.getX() - origin.x, p.y + e.getY() - origin.y);
            }
        });
    }
}
